package com.abe.mvp.view.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;

import com.abe.config.Constants;
import com.abe.config.SerialPortConstants;
import com.abe.config.SettingParam;
import com.abe.config.TreadmillSericalPortUtils;
import com.abe.mvp.contact.SerialPortContact;
import com.abe.mvp.contact.SocketContact;
import com.abe.mvp.model.bean.DeviceBean;
import com.abe.mvp.model.bean.SerialPortDataBean;
import com.abe.mvp.model.bean.SerialPortParseBean;
import com.abe.mvp.model.bean.SettingBean;
import com.abe.mvp.model.bean.exercise.ExerciseGroupBean;
import com.abe.mvp.presenter.SerialPortPresenterImp;
import com.abe.mvp.presenter.SocketPresenterImp;
import com.abe.utils.CRCChecker;
import com.abe.utils.NormalUtils;
import com.abe.utils.ThreadPoolUtils;

@SuppressLint("SimpleDateFormat")
public class MainActivity extends MainViewActivity {
	/** 串口相关 */
	private SerialPortContact.Presenter serialPortPresenter;
	/** socket相关 */
	private SocketContact.Presenter socketPresenter;

	private SettingBean settingBean;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		serialPortPresenter = new SerialPortPresenterImp(this);
		socketPresenter = new SocketPresenterImp(this);
		serialPortPresenter
				.openSerialPort(SerialPortConstants.SerialPort_ttys0);
		settingBean = SettingParam.getSettingBean();
		socketPresenter.openSocket(settingBean.getSocketIp(),
				settingBean.getSocketPort());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (serialPortPresenter != null) {
			serialPortPresenter.closeSerialPort();
			serialPortPresenter = null;
		}
		if (socketPresenter != null) {
			socketPresenter.closeSocket();
			socketPresenter = null;
		}
	}

	/********************************** fragment相关 *************************************/

	@Override
	public void chooseVideo() {
		switch (videoStatus) {
		case Constants.VideoGone:
			/** 需要时加载 */
			initCoverFlowAndVideo();
			videoStatus = Constants.CoverFlowVisible;
			/** 展示画廊 */
			localSendEmptyMessage(SHOW_COVERFLOW);
			break;
		case Constants.VideoPlayGone:
			videoStatus = Constants.VideoPlayVisible;
			/** 展示视频 */
			localSendEmptyMessage(SHOW_VIDEO);
			break;
		default:
			break;
		}
	}

	@Override
	public void setSpeed(float speed) {
		serialPortPresenter.sendCommand(TreadmillSericalPortUtils
				.getSetSpeedCommand(speed));
		ThreadPoolUtils.execute(new DelaySendSpeedSlope());
		sendCommandFlag = 1;
		isSetQtCommand = true;
	}

	@Override
	public void setSlope(float slope) {
		serialPortPresenter.sendCommand(TreadmillSericalPortUtils
				.getSetSlopeCommand(slope));
		ThreadPoolUtils.execute(new DelaySendSpeedSlope());
		sendCommandFlag = 1;
		isSetQtCommand = true;
	}

	@Override
	public void requestStart() {
		if (!exerciseStatus) {
			byte[] start = CRCChecker
					.getSendBuf(TreadmillSericalPortUtils.SET_START);
			serialPortPresenter.sendCommand(start);
			sendCommandFlag = 1;
			isSetStartStopCommand = true;
		}
	}

	@Override
	public void requestStop() {
		if (exerciseStatus) {
			/** 跑步机停止 */
			NormalUtils.saveCrashInfo2File("主动", "SET_STOP");
			byte[] stop = CRCChecker
					.getSendBuf(TreadmillSericalPortUtils.SET_STOP);
			serialPortPresenter.sendCommand(stop);
			sendCommandFlag = 1;
			isSetStartStopCommand = true;
		}
	}

	@Override
	public void startBack() {
		ThreadPoolUtils.execute(new WaitThread());
	}

	@Override
	public void stopBack(Boolean isDJSEnd, ExerciseGroupBean groupBean) {
		isFragmentRequestStop = isDJSEnd;
		/** 当前心率 */
		String bpm = top_infos.get(1).getData();
		float distance = Constants.keepDecimal(groupBean.getDistance() / 1000,
				1);
		int cll = (int) groupBean.getCalorie();
		float speed = Constants.SpeedConvertByMS(Constants.keepDecimal(
				groupBean.getAverageSpeed(), 1));
		float slope = Constants.keepDecimal(groupBean.getAverageSlope(), 1);
		String time = Constants.formatTime(groupBean.getKeepTime());
		socketPresenter.sendSocketCommand(Constants.getSocketCommand(
				current_user.getUser().getUserName(), cll, speed, time,
				distance, slope, bpm, current_user.getUser().getHeadimgurl()));
		if (!isFragmentRequestStop) {
			/** 锻炼数据 */
			showExerciseGroupData(groupBean);
		} else {
			fragmentRequestStopTempBean = groupBean;
			/** 发停止命令 */
			requestStop();
		}
	}

	@Override
	public void fragmentReady() {
		switch (currentTabFlag) {
		case SELECT_MOTOR_PATTERN:
			break;
		case SELECT_TARGET:
			fragment.selectPosition(currentTabPos);
			break;
		case SELECT_TRAIL:
			fragment.selectPosition(currentTabPos);
			break;
		}
	}

	@Override
	public void updateExercise(ExerciseGroupBean bean) {
		/** 刷新顶部显示 */
		switch (currentTabFlag) {
		case SELECT_MOTOR_PATTERN:
			localSendMessage(Constants.MainTopTime,
					Constants.formatTime(bean.getKeepTime()));
			localSendMessage(Constants.MainTopCalorie,
					String.valueOf((int) bean.getCalorie()));
			localSendMessage(Constants.MainTopDistance,
					String.valueOf(Constants.keepDecimal(
							bean.getDistance() / 1000, 2)));
			localSendMessage(Constants.MainTopSteps,
					Constants.getSteps(bean.getDistance()));
			break;
		case SELECT_TARGET:
			localSendMessage(Constants.MainTopSteps,
					Constants.getSteps(bean.getDistance()));
			String djs;
			switch (currentTabPos) {
			case 0:
				djs = Constants.formatTime(bean.getMaxNum()
						- bean.getKeepTime());
				localSendMessage(Constants.MainTopTime, djs);
				localSendMessage(Constants.MainTopCalorie,
						String.valueOf((int) bean.getCalorie()));
				localSendMessage(Constants.MainTopDistance,
						String.valueOf(Constants.keepDecimal(
								bean.getDistance() / 1000, 2)));
				break;
			case 2:
				int x = (int) (bean.getMaxNum() - bean.getCalorie());
				djs = x > 0 ? String.valueOf(x) : "0";
				localSendMessage(Constants.MainTopCalorie, djs);
				localSendMessage(Constants.MainTopTime,
						Constants.formatTime(bean.getKeepTime()));
				localSendMessage(Constants.MainTopDistance,
						String.valueOf(Constants.keepDecimal(
								bean.getDistance() / 1000, 2)));
				break;
			case 1:
				djs = String.valueOf(Constants.keepDecimal(
						(bean.getMaxNum() - bean.getDistance()) / 1000, 2));
				localSendMessage(Constants.MainTopDistance, djs);
				localSendMessage(Constants.MainTopTime,
						Constants.formatTime(bean.getKeepTime()));
				localSendMessage(Constants.MainTopCalorie,
						String.valueOf((int) bean.getCalorie()));
				break;
			}
			break;
		case SELECT_TRAIL:
			localSendMessage(Constants.MainTopTime,
					Constants.formatTime(bean.getKeepTime()));
			localSendMessage(Constants.MainTopCalorie,
					String.valueOf((int) bean.getCalorie()));
			localSendMessage(Constants.MainTopDistance,
					String.valueOf(Constants.keepDecimal(
							bean.getDistance() / 1000, 2)));
			localSendMessage(Constants.MainTopSteps,
					Constants.getSteps(bean.getDistance()));
			break;
		}

		/** 当前心率 */
		String bpm = top_infos.get(1).getData();
		float distance = Constants.keepDecimal(bean.getDistance() / 1000, 1);
		int cll = (int) bean.getCalorie();
		String time = Constants.formatTime(bean.getKeepTime());
		socketPresenter.sendSocketCommand(Constants.getSocketCommand(
				current_user.getUser().getUserName(), cll, current_speed, time,
				distance, current_slope, bpm, current_user.getUser()
						.getHeadimgurl()));
		if (bean.getKeepTime() % 10 == 0) {
			socketPresenter.checkScoket();
		}
	}

	/********************************* 串口相关 **************************************/
	/** 串口连接 */
	@Override
	public void onConnectSuccess() {
	}

	/** 串口命令下发 */
	@Override
	public void onSendDataSuccess() {
	}

	/** 串口数据接收 */
	@Override
	public void onReceiveDataSuccess(SerialPortDataBean data) {
		SerialPortParseBean parseBean = TreadmillSericalPortUtils.parse(data);
		if (parseBean.isVerifyStatus()) {
			/** 在停止的状态下，只有设置启动与读命令可以执行 */
			if (parseBean.getUseType() == 0) {
				/** 读操作返回成功 */
				DeviceBean bean = parseBean.getReadData();
				/** 更新心率 */
				localSendMessage(Constants.MainTopHeartRate, bean.getBpm());
				/** 更新锻炼状态 */
				boolean new_status = bean.isDeviceStart();
				if (exerciseStatus != new_status) {
					exerciseStatus = new_status;
					if (exerciseStatus) {
						localSendEmptyMessage(SHOW_DJS);
					} else {
						localSendEmptyMessage(STOP_SUCCESS);
					}
				}
				/** 更新速度 */
				float new_speed = bean.getSpeed();
				if (new_speed != current_speed) {
					current_speed = new_speed;
					localSendEmptyMessage(SET_SPEED);
				}
				/** 更新坡度 */
				float new_slope = bean.getSlope();
				if (new_slope != current_slope) {
					current_slope = new_slope;
					localSendEmptyMessage(SET_SLOPE);
				}
			} else {
				/** 写操作成功 */
				if (!exerciseStatus && isSetStartStopCommand) {
					exerciseStatus = true;
					localSendEmptyMessage(START_SUCCESS);
					isSetStartStopCommand = false;
				} else if (exerciseStatus && isSetStartStopCommand) {
					/** 在启动状态下设置关闭成功 */
					exerciseStatus = false;
					localSendEmptyMessage(STOP_SUCCESS);
					isSetStartStopCommand = false;
				}

				if (isSetQtCommand) {
					isSetQtCommand = false;
				}
			}
			sendCommandFlag = 0;
		} else {
			/** 数据校验失败 */
		}
	}

	@Override
	public void onCloseSuccess() {
	}

	/** 串口错误日志 */
	@Override
	public void onError(String errorMsg) {
		showToast(errorMsg);
	}

	/** 发送线程，现在有未反馈的命令，超时设置为150ms */
	class WaitThread implements Runnable {
		@Override
		public void run() {
			/** 读串口 */
			byte[] READ_DATA = CRCChecker
					.getSendBuf(TreadmillSericalPortUtils.READ_DATA);
			while (exerciseStatus) {
				try {
					Thread.sleep(500);
					int time = 0;
					if (sendCommandFlag != 0 && time < 150) {
						Thread.sleep(1);
						time++;
					}
					if (serialPortPresenter != null && !isSetStartStopCommand
							&& !isSetQtCommand) {
						serialPortPresenter.sendCommand(READ_DATA);
						isSetQtCommand = false;
						isSetStartStopCommand = false;
					}
					sendCommandFlag = 2;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/********************************** socket相关 *************************************/
	@Override
	public void onSocketConnectSuccess() {
	}

	@Override
	public void onSocketCloseSuccess() {
	}

	@Override
	public void onSocketSendDataSuccess() {
	}

	@Override
	public void onSocketReceiveDataSuccess(String receiveMsg) {
	}

	@Override
	public void onSocketError(String errorMsg) {
		/** socket异常 */
		if (socketPresenter != null) {
			/** 开启socket轮询来一直请求连接socket */
			socketPresenter.openSocket(settingBean.getSocketIp(),
					settingBean.getSocketPort());
		}
	}

}
